<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="value" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-if="showProgress" type="circle" :percentage="pagepercent" class="progress" />
    </el-upload>
  </div>
</template>

<script>
var COS = require('cos-js-sdk-v5')
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: '',
      pagepercent: 0,
      showProgress: false
    }
  },
  methods: {
    upload(res) {
      const cos = new COS({
        SecretId: 'AKIDcrqZ2FBrGOFo67rKWR5SXMuBAsJTLwGJ', // 身份识别ID
        SecretKey: 'nJZYHjutb2C5h14rMaXHkRs2vXsviESP' // 身份秘钥
      })
      this.showProgress = true
      if (res.file) {
        cos.putObject(
          {
            Bucket: 'lulu-1307394463' /* 必须 */,
            Region: 'ap-beijing' /* 存储桶所在地域，必须字段 */,
            Key: res.file.name /* 必须 */,
            StorageClass: 'STANDARD',
            Body: res.file, // 上传文件对象
            onProgress: (progressData) => {
              this.pagepercent = progressData.percent * 100
            }
          }, (err, data) => {
            // console.log(err || data)
            if (err) {
              return new Error(err)
            }
            // 上传成功
            if (data.statusCode === 200) {
            //   this.imageUrl = `https://${data.Location}`
              this.showProgress = false
              this.$emit('input', `https://${data.Location}`)
            }
          }
        )
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.progress{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);

}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
